package com.csii.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csii.core.util.TenantContext;
import com.csii.user.entity.*;
import com.csii.user.mapper.*;
import lombok.extern.slf4j.Slf4j;
import com.csii.user.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements ISysTenantService {

    @Autowired
    private SysTenantInitDataMapper sysTenantInitDataMapper;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private SysDictMapper sysDictMapper;
    @Autowired
    private SysDictItemMapper sysDictItemMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    private SysFillRuleMapper sysFillRuleMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initTenant(SysTenant sysTenant) {
        if (super.save(sysTenant)){
            /*//查询初始化数据
            LambdaQueryWrapper<SysTenantInitData> wrapper = new LambdaQueryWrapper(SysTenantInitData.class);
            Map<String, String> typeAndData = sysTenantInitDataMapper.selectList(wrapper).stream().collect(Collectors.toMap(SysTenantInitData::getType, SysTenantInitData::getData, (key1, key2) -> key2));
            List<String> menuIds = new ArrayList<>();
            //记录原始tenantId
            String originTenantId = TenantContext.getTenant();
            //修改TenantId上下文, mybatis拦截器会读取上下中的tenantId 写入数据库
            TenantContext.setTenant(sysTenant.getId());
            //初始化菜单
            insertSysPermissionTree(JSON.parseArray(typeAndData.get("initMenu"), Map.class),null,menuIds);
            //初始化字典
            //insertSysDict(JSON.parseArray(typeAndData.get("initDict"), Map.class));

            //初始化规则数据
            insertSysFillRule(JSON.parseArray(typeAndData.get("initFillRule"), SysFillRule.class));

            //初始化角色和菜单关系
            insertSysRolePermission(menuIds);
            //还原
            TenantContext.setTenant(originTenantId);*/
        }
    }

//    private String insertSysRole(){
//        SysRole sysRole = new SysRole();
//        sysRole.setRoleName("管理员");
//        sysRole.setRoleCode("admin");
//        sysRoleMapper.insert(sysRole);
//        return sysRole.getId();
//    }

    private void insertSysRolePermission(List<String> menuIds){
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper(SysRole.class);
        wrapper.eq(SysRole::getRoleCode,"admin");
        SysRole sysRole = sysRoleMapper.selectOne(wrapper);
        SysRolePermission sysRolePermission = new SysRolePermission();
        sysRolePermission.setRoleId(sysRole.getId());
        for (String id : menuIds) {
            sysRolePermission.setId(null);
            sysRolePermission.setPermissionId(id);
            sysRolePermissionMapper.insert(sysRolePermission);
        }
    }

    private void insertSysDict(List<Map> data){
        for (Map map : data) {
            SysDict sysDict = BeanUtil.mapToBean(map, SysDict.class,false);
            sysDict.setId(null);
            sysDict.setCreateTime(null);
            sysDict.setCreateBy("admin");
            sysDict.setUpdateTime(null);
            sysDict.setUpdateBy(null);
            sysDictMapper.insert(sysDict);
            List<Map> children = (List<Map>) map.get("children");
            if (children != null && children.size() > 0){
                for (Map childMap : children) {
                    SysDictItem sysDictItem = BeanUtil.mapToBean(childMap, SysDictItem.class,false);
                    sysDictItem.setId(null);
                    sysDictItem.setDictId(sysDict.getId());
                    sysDictItem.setCreateTime(null);
                    sysDictItem.setCreateBy("admin");
                    sysDictItem.setUpdateTime(null);
                    sysDictItem.setUpdateBy(null);
                    sysDictItemMapper.insert(sysDictItem);
                }

            }
        }
    }


    private void insertSysFillRule(List<SysFillRule> data){
        data.forEach(sysFillRule -> {
            sysFillRule.setId(null);
            sysFillRule.setCreateTime(null);
            sysFillRule.setCreateBy("admin");
            sysFillRule.setUpdateTime(null);
            sysFillRule.setUpdateBy(null);
            sysFillRuleMapper.insert(sysFillRule);
        });
    }

    private void insertSysPermissionTree(List<Map> data,String parentId,List<String> ids){
        for (Map map : data) {
            SysPermission sysPermission = BeanUtil.mapToBean(map, SysPermission.class,false);
            sysPermission.setId(null);
            sysPermission.setParentId(parentId);
            sysPermission.setCreateTime(null);
            sysPermission.setCreateBy("admin");
            sysPermission.setUpdateTime(null);
            sysPermission.setUpdateBy(null);
            sysPermissionMapper.insert(sysPermission);
            ids.add(sysPermission.getId());
            List<Map> children = (List<Map>) map.get("children");
            if (children != null && children.size() > 0){
                insertSysPermissionTree(children,sysPermission.getId(),ids);
            }
        }
    }

}
